package com.heima.controller;

import com.heima.common.Result;
import com.heima.domain.dto.SkuDto;
import com.heima.service.OSSAliyunFileStorageService;
import com.heima.service.SkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/vm-service/sku")
@Api(tags = "商品管理")
public class SkuController {

    @Autowired
    private OSSAliyunFileStorageService fileStorageService;

    @Autowired
    private SkuService skuService;

    @PostMapping("/fileUpload")
    @ApiOperation("文件上传")
    public String fileUpload( MultipartFile fileName) throws IOException {
        // 校验是否为图片文件
        try {
            BufferedImage bufferedImage = ImageIO.read(fileName.getInputStream());
        } catch (Exception e) {
            throw new RuntimeException("上传图片失败");
        }

        if (fileName.getSize() == 0) {
            throw new RuntimeException("上传图片不能为空");
        }
        String originalFilename = fileName.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fName = UUID.randomUUID().toString() + extension;
        String url = fileStorageService.store(fName,fileName.getInputStream());
        return url;
    }

    @PostMapping
    @ApiOperation("新增商品")
    public Boolean addSku(@RequestBody SkuDto dto){
        Boolean flag = skuService.addSku(dto);
        return flag;
    }

    @GetMapping("/search")
    @ApiOperation("分页查询商品")
    public Result getSkuByPage(@RequestParam(required = false) Integer pageIndex,
                               @RequestParam(required = false) Integer pageSize,
                               @RequestParam(required = false) String skuName){
        Result result = skuService.getSkuByPage(pageIndex,pageSize,skuName);
        return result;
    }

    @PutMapping("/{skuId}")
    @ApiOperation("修改商品")
    public Boolean updateSku(@RequestBody SkuDto dto,@PathVariable Long skuId){
       Boolean flag = skuService.updateSku(dto,skuId);
       return flag;
    }
}
